package com.pa.authorization.config;

import com.lww.springcloudapi.entity.TabEmployee;
import com.pa.authorization.service.TabEmployeeLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //密码模式才需要配置,认证管理器
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .anyRequest().permitAll()

                .and()
                .formLogin()

                .and()
                .logout();

        //        没有权限默认进入登录页面
//        http.formLogin().loginPage("/employee-login/toLogin") // default is /login with an HTTP get
//                .loginProcessingUrl("/employee-login/login");
    }

    @Autowired
    TabEmployeeLoginService tabEmployeeLoginService;

    @Bean
    public UserDetailsService userDetailsService() {
        return s -> {
            TabEmployee queryByName = tabEmployeeLoginService.findQueryByName(s);
            if (queryByName != null) {
                return queryByName;
            }
            return null;
        };
    }
}